<template>
  <div class="koi-flex">
    <KoiCard>
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true">
        <el-form-item label="登录账号" prop="loginName">
          <el-input placeholder="请输入登录账号" v-model="searchParams.login_name" clearable style="width: 200px"
            @keyup.enter.native="handleListPage"></el-input>
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input placeholder="请输入用户名称" v-model="searchParams.user_name" clearable style="width: 200px"
            @keyup.enter.native="handleListPage"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input placeholder="请输入手机号" v-model="searchParams.phone" clearable style="width: 200px"
            @keyup.enter.native="handleListPage"></el-input>
        </el-form-item>
        <el-form-item label="登录时间" prop="loginTime">
          <el-date-picker v-model="dateRange" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss"
            start-placeholder="开始日期" range-separator="至" end-placeholder="结束日期"
            :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain v-debounce="handleSearch">搜索</el-button>
          <el-button type="danger" icon="refresh" plain v-throttle="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5" v-auth="['system:admin:add']">
          <el-button type="primary" icon="plus" plain @click="handleAdd()">新增</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['system:admin:update']">
          <el-button type="success" icon="edit" plain @click="handleUpdate()" :disabled="single">修改</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['system:admin:delete']">
          <el-button type="danger" icon="delete" plain @click="handleBatchDelete()" :disabled="multiple">删除</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['system:admin:role']">
          <el-button type="primary" icon="edit" plain @click="handleAssignRoles()" :disabled="single">分配角色</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['system:admin:resetPwd']">
          <el-button type="primary" icon="edit" plain @click="handleResetPwd()" :disabled="single">重置密码</el-button>
        </el-col>
        <el-col :span="1.5" v-auth="['system:admin:resetGA']">
          <el-button type="primary" icon="edit" plain @click="handleResetGa()" :disabled="single">重置GA</el-button>
        </el-col>
        <KoiToolbar v-model:showSearch="showSearch" @refreshTable="handleListPage"></KoiToolbar>
      </el-row>

      <div class="h-20px"></div>
      <!-- 数据表格 :data="tableList" -->
      <el-table v-loading="loading" border
        :data="tableList.slice((searchParams.page_index - 1) * searchParams.page_size, searchParams.page_index * searchParams.page_size)"
        empty-text="暂时没有数据哟" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" prop="id" width="80px" align="center" type="index"></el-table-column>
        <el-table-column label="登录账号" prop="login_name" width="120px" align="center"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="头像" prop="avatar" width="80px" align="center">
          <template #default="scope">
            <div class="flex justify-center">
              <el-image class="rounded-full w-36px h-36px" :preview-teleported="true"
                :preview-src-list="[scope.row.avatar]" :src="scope.row.avatar != null && scope.row.avatar != ''
                  ? scope.row.avatar
                  : 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
                  ">
                <template #error>
                  <el-icon class="c-[--el-color-primary]" :size="36">
                    <CircleCloseFilled />
                  </el-icon>
                </template>
              </el-image>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="用户名称" prop="user_name" width="120px" align="center"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="邮箱" prop="email" width="220px" align="center"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="手机号" prop="phone" width="150px" align="center"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="用户类型" prop="user_type" width="100px" align="center">
          <template #default="scope">
            <KoiTag :tagOptions="userTypeOptions" :value="scope.row.user_type"></KoiTag>
          </template>
        </el-table-column>
        <el-table-column label="用户性别" prop="gender" width="100px" align="center">
          <template #default="scope">
            <KoiTag :tagOptions="userSexOptions" :value="scope.row.gender"></KoiTag>
          </template>
        </el-table-column>
        <!-- 注意：如果后端数据返回的是字符串"0" OR "1"，这里的active-value AND inactive-value不需要加冒号，会认为是字符串，否则：后端返回是0 AND 1数字，则需要添加冒号 -->
        <el-table-column label="用户状态" prop="state" width="100px" align="center">
          <template #default="scope">
            <el-switch v-model="scope.row.state" active-text="启用" inactive-text="停用" :active-value="1"
              :inactive-value="0" :inline-prompt="true" @change="handleSwitch(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="created_at" width="180px" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" width="200px" align="center"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="操作" align="center" width="150" fixed="right"
          v-auth="['system:admin:update', 'system:admin:delete']">
          <template #default="{ row }">
            <el-tooltip content="修改" placement="top">
              <el-button type="primary" icon="Edit" circle plain @click="handleUpdate(row)"
                v-auth="['system:admin:update']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button type="danger" icon="Delete" circle plain @click="handleDelete(row)"
                v-auth="['system:admin:delete']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="h-20px"></div>
      <!-- {{ searchParams.pageNo }} --- {{ searchParams.pageSize }} -->
      <!-- 分页 -->
      <el-pagination background v-model:current-page="searchParams.page_index"
        v-model:page-size="searchParams.page_size" v-show="total > 0" :page-sizes="[10, 20, 50, 100, 200]"
        layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleListPage"
        @current-change="handleListPage" />

      <!-- 添加 OR 修改 -->
      <KoiDrawer ref="koiDrawerRef" :title="title" @koiConfirm="handleConfirm" @koiCancel="handleCancel"
        :loading="confirmLoading">
        <template #content>
          <el-form ref="formRef" :rules="rules" :model="form" label-width="80px" status-icon>
            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="登录账号" prop="login_name">
                  <el-input v-model="form.login_name" placeholder="请输入登录账号" clearable />
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="用户名称" prop="user_name">
                  <el-input v-model="form.user_name" placeholder="请输入用户名称" clearable />
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="用户类型" prop="user_type">
                  <el-select placeholder="请选择用户类型" v-model="form.user_type" clearable>
                    <el-option v-for="item in userTypeOptions" :key="item.dict_value" :label="item.dict_label"
                      :value="item.dict_value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="用户状态" prop="state">
                  <el-select v-model="form.state" placeholder="请选择用户状态" clearable>
                    <el-option label="启用" value="1" />
                    <el-option label="停用" value="0" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="用户头像" prop="avatar">
                  <KoiUploadImage v-model:imageUrl="form.avatar">
                    <template #content>
                      <el-icon>
                        <Avatar />
                      </el-icon>
                      <span>请上传头像</span>
                    </template>
                    <template #tip>图片最大为 3M</template>
                  </KoiUploadImage>
                  <!-- <el-input v-model="form.avatar" placeholder="请输入用户头像地址" clearable /> -->
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="邮箱" prop="email">
                  <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                <el-form-item label="用户备注" prop="remark">
                  <el-input v-model="form.remark" :rows="5" type="textarea" placeholder="请输入用户备注" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <!-- {{ form }} -->
        </template>
      </KoiDrawer>

      <KoiDialog ref="koiDialogRef" title="分配角色" :height="450" :loading="confirmLoading" :footerHidden="true">
        <template #content>
          <div class="flex flex-justify-center">
            <el-transfer :props="{
              key: 'role_code',
              label: 'role_name'
            }" :titles="['角色列表', '拥有角色']" target-order="original" filterable filter-placeholder="关键字搜索" :format="{
              noChecked: '${total}',
              hasChecked: '${checked}/${total}'
            }" v-model="roleSelectedList" :data="roleAllList" @change="handleTransferChange" />
          </div>
        </template>
      </KoiDialog>

      <KoiDialog ref="koiDialogResetPwdRef" title="重置密码" :height="450" @koiConfirm="" @koi="" :loading="confirmLoading"
        :footerHidden="true">
        <template #content>
          <div class="flex flex-justify-center">
            <el-form ref="formRestPwdRef" :rules="rulesResetPwd" :model="formResetPwd" label-width="80px" status-icon>
              <el-row>
                <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                  <el-form-item label="输入密码" prop="pwd_first">
                    <el-input v-model="formResetPwd.pwd_first" placeholder="请输入密码" clearable />
                  </el-form-item>
                </el-col>
                <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                  <el-form-item label="再次输入密码" prop="pwd_secode">
                    <el-input v-model="formResetPwd.pwd_secode" placeholder="再次输入密码" clearable />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </template>
      </KoiDialog>
      <KoiDialog ref="koiDialogResetGaRef" title="重置GA" :height="450" :loading="confirmLoading" :footerHidden="true">
        <template #content>
          <div class="flex flex-justify-center">
            <el-form ref="formRestGaRef" :rules="rulesResetGa" :model="formResetGa" label-width="80px" status-icon>
              <el-row>
                <el-col :xs="{ span: 24 }" :sm="{ span: 24 }">
                  <el-form-item label="请输入GA" prop="ga_secret">
                    <el-input v-model="formResetGa.ga_secret" placeholder="请输入GA" clearable />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </template>
      </KoiDialog>
    </KoiCard>
  </div>
</template>

<script setup lang="ts" name="userPage">
// 已使用字典案例
import { nextTick, ref, reactive, onMounted } from "vue";
// @ts-ignore
import {
  koiMsgSuccess,
  koiNoticeSuccess,
  koiNoticeError,
  koiMsgError,
  koiMsgWarning,
  koiMsgBox,
  koiMsgInfo,
  formatDate
} from "@/utils/koi.ts";
// @ts-ignore
import { listPage, getById, add, update, deleteById, batchDelete, updateStatus } from "@/api/system/user/index.ts";
import { listAll, listByUserId, assignUserRole } from "@/api/system/role/index.ts";
// @ts-ignore
import { listDataByType } from "@/api/system/dict/data/index.ts";
import { koiDatePicker } from "@/utils/index.ts";

// 数据表格加载页面动画
const loading = ref(false);
/** 是否显示搜索表单 */
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 数据表格数据
const tableList = ref<any>([

]);

// 选中数组
const ids = ref([]);
// 非单个禁用
const single = ref<boolean>(true);
// 非多个禁用
const multiple = ref<boolean>(true);

// 查询参数
const searchParams = ref({
  page_index: 1, // 第几页
  page_size: 10, // 每页显示多少条
  login_name: "",
  user_name: "",
  phone: ""
});

const total = ref<number>(0);

// 重置搜索参数
const resetSearchParams = () => {
  searchParams.value = {
    page_index: 1,
    page_size: 10,
    login_name: "",
    user_name: "",
    phone: ""
  };
  dateRange.value = [];
};

/** 搜索 */
const handleSearch = () => {
  console.log("搜索");
  searchParams.value.page_index = 1;
  handleListPage();
};

/** 重置 */
const resetSearch = () => {
  console.log("重置搜索");
  resetSearchParams();
  handleListPage();
};

// 时间
const dateRange = ref();
/** @current-change：点击分页组件页码发生变化：例如：切换第2、3页 OR 上一页 AND 下一页 OR 跳转某一页 */
/** @size-change：点击分页组件下拉选中条数发生变化：例如：选择10条/页、20条/页等 */
// 分页查询，@current-change AND @size-change都会触发分页，调用后端分页接口
/** 数据表格 */
const handleListPage = async () => {
  total.value = 15;
  try {
    loading.value = true;
    tableList.value = []; // 重置表格数据
    const res: any = await listPage(
      koiDatePicker(searchParams.value, dateRange.value)
    );
    tableList.value = res.data.list;
    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试");
    loading.value = false;
  }
};

// 静态页面防止报错(可直接删除)
// @ts-ignore
const handleStaticPage = () => {
  listPage(koiDatePicker(searchParams.value, dateRange.value));
};

/** 数据表格[删除、批量删除等刷新使用] */
const handleTableData = async () => {
  try {
    const res: any = await listPage(koiDatePicker(searchParams.value, dateRange.value));
    // console.log("用户数据表格数据->", res.data);
    tableList.value = res.data.list;
    total.value = res.data.total;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试");
  }
};

onMounted(() => {
  // 获取数据表格数据
  handlerUserType();
  handlerUserGender();
  handleListPage();
});

// 翻译数据[用户类型]
const userTypeOptions = ref();
/** 字典翻译tag */
const handlerUserType = async () => {
  try {
    const res: any = await listDataByType("sys_user_type");
    userTypeOptions.value = res.data;
  } catch (error) {
    console.log(error);
    koiMsgError("数据字典查询失败，请刷新重试");
  }
};

// 翻译数据[用户性别]
const userSexOptions = ref();
/** 字典翻译tag */
const handlerUserGender = async () => {
  try {
    const res: any = await listDataByType("sys_user_sex");
    userSexOptions.value = res.data;
  } catch (error) {
    console.log(error);
    koiMsgError("数据字典查询失败，请刷新重试");
  }
};


/** 是否多选 */
const handleSelectionChange = (selection: any) => {
  // console.log(selection);
  ids.value = selection.map((item: any) => item.id);
  single.value = selection.length != 1; // 单选
  multiple.value = !selection.length; // 多选
};

/** 添加 */
const handleAdd = () => {
  // 打开弹出框
  koiDrawerRef.value.koiOpen();
  koiMsgSuccess("添加");
  // 重置表单
  resetForm();
  // 标题
  title.value = "用户添加";
  form.value.state = "1";
};

/** 回显数据 */
const handleEcho = async (id: any) => {
  if (id == null || id == "") {
    koiMsgWarning("请选择需要修改的数据");
    return;
  }
  try {
    const res: any = await getById({ user_id: id });
    console.log(res.data);
    form.value = res.data;
  } catch (error) {
    koiNoticeError("数据获取失败，请刷新重试");
    console.log(error);
  }
};

/** 修改 */
const handleUpdate = async (row?: any) => {
  // 打开弹出框
  koiDrawerRef.value.koiOpen();
  // 重置表单
  resetForm();
  // 标题
  title.value = "用户修改";
  const userId = row ? row.id : ids.value[0];
  if (userId == null || userId == "") {
    koiMsgError("请选中需要修改的数据");
  }
  console.log(userId);
  // 回显数据
  handleEcho(userId);
};

/** 添加 AND 修改抽屉 */
const koiDrawerRef = ref();
// 标题
const title = ref("用户类型管理");
// form表单Ref
const formRef = ref<any>();

// form表单
let form = ref<any>({
  user_name: "",
  user_type: "",
  state: "",
  avatar: "",
  phone: "",
  remark: ""
});

/** 清空表单数据 */
const resetForm = () => {
  // 等待 DOM 更新完成
  nextTick(() => {
    if (formRef.value) {
      // 重置该表单项，将其值重置为初始值，并移除校验结果
      formRef.value.resetFields();
    }
  });
  form.value = {
    user_name: "",
    user_type: "",
    state: "",
    avatar: "",
    phone: "",
    remark: ""
  };
};

/** 表单规则 */
const rules = reactive({
  login_name: [{ required: true, message: "请输入用户账号", trigger: "blur" }],
  user_name: [{ required: true, message: "请输入用户名字", trigger: "blur" }],
  user_type: [{ required: true, message: "请输入用户类型", trigger: "blur" }],
  state: [{ required: true, message: "请输入选择用户状态", trigger: "blur" }]
});

// 重置密码表单 ref
const formRestPwdRef = ref<any>();
let formResetPwd = ref<any>({


});

const rulesResetPwd = reactive({
  pwd_first: [{ required: true, message: "请输入密码", trigger: "blur" }],
  pwd_secode: [{ required: true, message: "请再次输入密码", trigger: "blur" }]
});

// 重置GA表单 ref
const formRestGaRef = ref<any>();
let formResetGa = ref<any>({

});
const rulesResetGa = reactive({
  ga_secret: [{ required: true, message: "请输入GA", trigger: "blur" }]
});



// 确定按钮是否显示loading
const confirmLoading = ref(false);
/** 确定  */
const handleConfirm = () => {
  if (!formRef.value) return;
  confirmLoading.value = true;
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      console.log("表单ID", form.value.userId);
      if (form.value.userId != null && form.value.userId != "") {
        try {
          await update(form.value);
          koiNoticeSuccess("修改成功");
          confirmLoading.value = false;
          koiDrawerRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiNoticeError("修改失败，请刷新重试");
        }
      } else {
        try {
          await add(form.value);
          koiNoticeSuccess("添加成功");
          confirmLoading.value = false;
          koiDrawerRef.value.koiQuickClose();
          resetForm();
          handleListPage();
        } catch (error) {
          console.log(error);
          confirmLoading.value = false;
          koiNoticeError("添加失败，请刷新重试");
        }
      }

      // let loadingTime = 1;
      // setInterval(() => {
      //   loadingTime--;
      //   if (loadingTime === 0) {
      //     koiNoticeSuccess("朕让你提交了么？信不信锤你");
      //     confirmLoading.value = false;
      //     resetForm();
      //     koiDrawerRef.value.koiQuickClose();
      //   }
      // }, 1000);
    } else {
      koiMsgError("验证失败，请检查填写内容");
      confirmLoading.value = false;
    }
  });
};

/** 取消 */
const handleCancel = () => {
  koiDrawerRef.value.koiClose();
};

/**
 * 更改用户的状态
 * 1.先判断用户状态与主键状态值是否一致
 * 2.若不一致那么更改状态
 * 3.若一致那么不执行
 */
const handleSwitch = (row: any) => {
  const originalState = row.state == 1 ? 0 : 1;
  let text = row.state == 1 ? "启用" : "停用";
  koiMsgBox("确认要[" + text + "]-[" + row.user_name + "]吗？")
    .then(async () => {
      if (!row.id || !row.state) {
        koiMsgWarning("请选择需要修改的数据");
        return;
      }
      try {
        await updateStatus(row.id, row.state);
        koiNoticeSuccess("修改成功");
      } catch (error) {
        console.log(error);
        handleTableData();
      }
    })
    .catch(() => {
      row.state = originalState;
    });
};

// 重置密码
const koiDialogResetPwdRef = ref();
const handleResetPwd = async () => {
  koiDialogResetPwdRef.value.koiOpen();
}

// 重置GA
const koiDialogResetGaRef = ref();
const handleResetGa = async () => {
  koiDialogResetGaRef.value.koiOpen();
}


// 分配角色弹出框
const koiDialogRef = ref();
/** 分配角色 */
const handleAssignRoles = async () => {
  // 获取选中的用户ID
  const userId = ids.value[0];
  if (!userId) {
    koiMsgWarning("请选择需要分配角色的用户");
    return;
  }

  try {
    // 获取所有角色列表
    const resAll: any = await listAll();
    if (resAll.code == 200) {
      roleAllList.value = resAll.data;
    }
    // 获取选中用户的角色列表
    const resLogin: any = await listByUserId({ "user_id": userId });
    if (resLogin.code == 200) {
      roleSelectedList.value = resLogin.data.map((role: any) => role.role_code);
    }
  } catch (error) {
    console.log(error);
    koiMsgError("加载角色数据失败");
  }
  koiDialogRef.value.koiOpen();
};
const roleSelectedList = ref([]);
const roleAllList = ref<any>([]);

// 右侧列表元素变化时触发
const handleTransferChange = async (value: any) => {

  const userId = ids.value[0];
  if (!userId) {
    koiMsgWarning("请选择需要分配角色的用户");
    return;
  }

  try {
    await assignUserRole({
      "user_id": userId,
      "role_codes": value
    });
    koiNoticeSuccess("分配角色成功");
  } catch (error) {
    console.log(error);
    handleAssignRoles();
    koiMsgError("分配角色失败，请重试");
  }
};

/** 删除 */
const handleDelete = (row: any) => {
  const id = row.userId;
  if (id == null || id == "") {
    koiMsgWarning("请选中需要删除的数据");
    return;
  }
  koiMsgBox("您确认需要删除用户名称[" + row.userTitle + "]么？")
    .then(async () => {
      try {
        await deleteById(id);
        handleTableData();
        koiNoticeSuccess("删除成功");
      } catch (error) {
        console.log(error);
        handleTableData();
        koiNoticeError("删除失败，请刷新重试");
      }
    })
    .catch(() => {
      koiMsgError("已取消");
    });
};

/** 批量删除 */
const handleBatchDelete = () => {
  if (ids.value.length == 0) {
    koiMsgInfo("请选择需要删除的数据");
    return;
  }
  koiMsgBox("您确认需要进行批量删除么？")
    .then(async () => {
      try {
        console.log("ids", ids.value);
        await batchDelete(ids.value);
        handleTableData();
        koiNoticeSuccess("批量删除成功");
      } catch (error) {
        console.log(error);
        koiNoticeError("批量删除失败，请刷新重试");
        handleTableData();
      }
    })
    .catch(() => {
      koiMsgError("已取消");
    });
};
</script>

<style lang="scss" scoped>
// 穿梭框高度调整
:deep(.el-transfer-panel__body) {
  height: 400px;
}
</style>
